﻿using AutoMapper;
using DereamWork.Web.API.Infrastructure;
using dreamwork.mobile.app.api.Infrastructure;
using dreamwork.mobile.app.api.Models.Data;
using dreamwork.mobile.app.api.Models.ViewModel;
using dreamwork.mobile.app.api.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Swashbuckle.AspNetCore.Swagger;
using System.Text;

namespace dreamwork.mobile.app.api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region AutoMapper

            services.AddAutoMapper(mapconfiguration =>
            {
                mapconfiguration.CreateMap<NormalUserRegisterViewModel, NormalUser>(MemberList.Source);
                mapconfiguration.CreateMap<NormalUserLoginViewModel, NormalUser>(MemberList.Source);
                mapconfiguration.CreateMap<NormalUserModifyViewModel, NormalUser>(MemberList.Source);

                mapconfiguration.CreateMap<TerminalUserRegisterViewModel, TerminalUser>(MemberList.Source);
                mapconfiguration.CreateMap<TerminalUserLoginViewModel, TerminalUser>(MemberList.Source);
                mapconfiguration.CreateMap<TerminalUserDetailViewModel, TerminalUser>(MemberList.Source);
                mapconfiguration.CreateMap<TerminalUserModifyViewModel, TerminalUser>(MemberList.Source);
                mapconfiguration.CreateMap<TerminalUserUpdatePositionViewModel, TerminalUser>(MemberList.Source);
            });
            #endregion

            #region DBProvider

            #region EF Memory
            services.AddDbContext<MobileAppDbContext>(options =>
            {
                options.UseInMemoryDatabase(databaseName: "dreamworkmobileapp");
                //options.UseSqlite("Data Source=Data/MobileData.db");
            });
            #endregion

            #region MongoDB
            services.AddTransient<IMongodbContext, MongodbContext>();
            services.AddTransient<INormalUserRepository, NormalUserMongoRepository>();
            services.AddTransient<ITerminalUserRepository, TerminalUserMongoRepository>();
            #endregion

            #endregion

            #region Authentication
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =>
          {
              options.Challenge = JwtBearerDefaults.AuthenticationScheme;
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuer = true,
                  ValidateAudience = false,
                  ValidateLifetime = true,
                  ValidateIssuerSigningKey = true,
                  ValidIssuer = Configuration["Jwt:Issuer"],
                  ValidAudience = Configuration["Jwt:Issuer"],
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
              };
          });

            #endregion

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices();

            #region Service
            services.AddTransient<INormalUserRegisterService, NormalUserRegisterService>();
            services.AddTransient<INormalUserService, NormalUserService>();

            services.AddTransient<ITerminalUserRegisterService, TerminalUserRegisterService>();
            services.AddTransient<ITerminalUserService, TerminalUserService>();

            services.AddTransient<ITokenService, TokenService>();
            #endregion

            #region Swagger
            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Info { Title = "Dreamwork Mobile API", Version = "v1" });
                options.OperationFilter<HttpAuthHeaderFilter>();
            });
            #endregion

            #region Cors
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
            #endregion

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseCors("CorsPolicy");
            app.UseSwagger();
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvcWithDefaultRoute();
            app.UseStaticFiles();
            app.UseSwagger()
               .UseSwaggerUI(c =>
             {
                 c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dreamwork.Mobile.API");
             });
        }
    }
}
